<script setup>
import Header from "@/components/layout/header.vue";
import { useRouter } from "vue-router";
import useUserStore from "@/store/modules/user";
import Echarts from "@/components/layout/echarts.vue";
import {
  AllReadAPI,
  GetMessageAPI,
  GetAuditListAPI,
  GetNoticeListAPI,
  GetMenuAPI,
  AddShortcutsAPI,
  GetShortcutsAPI,
  GetNoMessageAPI,
  GetCustomerSaleRankAPI, // 获取前五大客户销售占比
  GetSupplierSaleRankAPI, // 获取前五大供应商采购占比
  GetFinishAmountAPI, // 获取首页工作台成品库存金额
  GetRawAmountAPI, // 获取首页工作台原料库存金额
} from "@/api/index";
const { proxy } = getCurrentInstance();

const router = useRouter();

// 用户信息
const userStore = ref(useUserStore());

const drawer = ref(false); //抽屉状态

const tabPosition = ref("未读消息"); //抽屉内部按钮tabs

const TableData = ref([]); //抽屉内部表格数据

//抽屉内部表格分页参数
const drawerQuery = reactive({
  pageNum: 1,
  pageSize: 10,
});

//抽屉内部表格total
const state = reactive({
  total: 0,
});

// 审核代办枚举
const column = ref([
  {
    label: "单据名称",
    prop: "receiptName",
  },
  {
    label: "单据号",
    prop: "receiptNumber",
  },
  {
    label: "状态",
    prop: "statusDict",
  },
  {
    label: "内容",
    showText: true,
    prop: "receiptContent",
  },
  {
    label: "操作",
    prop: "x",
  },
]);

/**
 * ------------------------------快捷功能--------------------SAT----------->
 */

// 快捷列表对象
const pageObj = reactive({
  pageList: [], // 快捷列表
  disabled: false, // 是否禁用
  shortcutsList: [],
  shortcutsShow: false, // 快捷弹窗
  idStr: "",
});

// 快捷功能弹窗
const shortcutsAdd = () => {
  getMenuList();
  getShortcuts();
  pageObj.shortcutsShow = true;
};

// 右侧改变时
const rightPageChange = (val) => {
  if (val.length > 10) {
    pageObj.disabled = true;
  } else {
    pageObj.disabled = false;
  }
};

// 获取快捷列表
const getShortcuts = async () => {
  const { data: result } = await GetShortcutsAPI();
  pageObj.shortcutsList = result;
  pageObj.idStr = result.map((t) => t.menuId);
};

// 获取页面列表
const getMenuList = async () => {
  const { data: result } = await GetMenuAPI();
  console.log(result, "resultssss");
  pageObj.pageList = result;
};

// 快捷功能提交
const shortcutsSub = async () => {
  if (pageObj.disabled) return proxy.warningMsg("最多选择10条！");
  pageObj.btnloading = true;
  try {
    await AddShortcutsAPI({
      idStr: pageObj.idStr,
    });
    proxy.successMsg("切换成功！");
    getShortcuts();
    pageObj.shortcutsShow = false;
  } catch {
  } finally {
    pageObj.btnloading = false;
  }
};

const filterMethod = (query, item) => {
  return item.menuName.toLowerCase().includes(query.toLowerCase());
};
/**
 * ------------------------------快捷功能------------------END------------->
 */

/**
 * ------------------------------审核代办------------------SAT------------->
 */
const examineObj = reactive({
  // 审核代办总数
  auditAgentData: [],
  // 审核代办列表
  examineTable: [],
  pageNum: 1,
  pageSize: 10,
});

// 获取审核代办列表
const getAuditAgentData = async () => {
  // query.pageNum++
  if (examineObj.auditAgentData.length > examineObj.total) {
    return;
  }
  examineObj.auditAgentLoading = true;
  try {
    const result = await GetAuditListAPI({
      pageNum: examineObj.pageNum,
      pageSize: examineObj.pageSize,
    });
    examineObj.auditAgentData = result.rows;
    examineObj.total = result.total;
  } catch (err) {
    console.log(err);
  } finally {
    examineObj.auditAgentLoading = false;
  }
};

// 计算审核代办状态 为待处理的总数
const auditAgentTotal = computed(() => {
  const arr = examineObj.examineTable.filter((t) => t.status != 3);
  if (arr?.length > 0) {
    return arr.length;
  } else {
    return 0;
  }
});

getAuditAgentData();
/**
 * ------------------------------审核代办------------------END------------->
 */

/**
 * ------------------------------消息提醒------------------SAT------------->
 */

// 消息提醒
const msgObj = reactive({
  messageData: [], // 消息列表
  msgLoading: false, // 加载状态
  pageNum: 1,
  pageSize: 9999999,
});

// 已读
// const read = async (val) => {
//   if (val.readMark == 2) {
//     await AllReadAPI({ id: val.id });
//     val.readMark = 1;
//     router.push("/approval/daiban");
//   }
// };

// 全部已读
const allRead = async () => {
  await AllReadAPI({ id: "" });
  msgObj.messageData = [];
  getMessage();
};

// 获取消息提醒列表
const getMessage = async () => {
  msgObj.msgLoading = true;
  try {
    const result = await GetMessageAPI();
    console.log(result, "result");
    msgObj.messageData = result.rows;
    msgObj.total = result.total;
    userStore.setMsgTotal();
  } catch {
  } finally {
    msgObj.msgLoading = false;
  }
  userStore.setMsgTotal();
};

// 计算未读消息
const msgTotal = computed(() => {
  const arr = msgObj.messageData.filter((t) => t.readMark == 2);
  if (arr?.length > 0) {
    return arr.length;
  } else {
    return 0;
  }
});

const loadingChange = (val) => {
  msgObj.pageNum++;
  // if (msgObj.messageData.length > totalMsg.value) return
  // getMessage()
};
getMessage();
getShortcuts();

/**
 * ------------------------------消息提醒------------------END------------->
 */

/**
 * ------------------------------echarts--占比-------------SAT------------->
 */

const echartsObj = reactive({
  customerData: {}, // 前五大客户销售占比
  supplierData: {}, // 前五大供应商销售占比
  finishAmount: {}, // 获取首页工作台成品库存金额
  rawAmountData: {}, // 获取首页工作台原料库存金额
});

//  获取前五大客户销售占比（元）
const getCustomerSaleRank = async () => {
  const { data: result } = await GetCustomerSaleRankAPI();
  echartsObj.customerData = result.map((t) => ({
    name: t.publicName,
    value: Number(t.salePriceTotal),
  }));
};

//  获取前五大供应商采购占比（元）
const getSupplierSaleRank = async () => {
  const { data: result } = await GetSupplierSaleRankAPI();
  echartsObj.supplierData = result.map((t) => ({
    name: t.publicName || "错误",
    value: Number(t.salePriceTotal),
  }));
};

//  获取首页工作台成品库存金额
const getFinishAmount = async () => {
  const { data: result } = await GetFinishAmountAPI();
  echartsObj.finishAmount = result.map((t) => ({
    name: t.publicName,
    value: Number(t.salePriceTotal),
  }));
};

//  获取原料库存金额
const getRawAmount = async () => {
  const { data: result } = await GetRawAmountAPI();
  echartsObj.rawAmountData = result.map((t) => ({
    name: t.publicName,
    value: Number(t.salePriceTotal),
  }));
};

//抽屉
const isChouti = () => {
  drawer.value = true;
  getList();
};

//获取抽屉内部表格数据
const getList = async () => {
  const res = await GetMessageAPI(drawerQuery);
  TableData.value = res.rows;
  state.total = parseInt(res.total);
};

// getCustomerSaleRank()
// getSupplierSaleRank()
// getFinishAmount()
// getRawAmount()

watch(
  () => tabPosition.value,
  (val) => {
    val == "未读消息"
      ? (drawerQuery.readMark = "2")
      : (drawerQuery.readMark = "1");
    getList();
  },
  { deep: true, immediate: true }
);
</script>
<template>
  <div>
    <Header v-if="userStore.workbenchDataType == 1" />
    <el-card class="shortcuts-box mt20">
      <template #header>
        <div class="card-header flex-items-center">
          <div class="flex-items-center">
            <el-icon
              color="#006CB6"
              size="20px"
              class="cup mr10"
              @click="shortcutsAdd"
            >
              <Setting />
            </el-icon>
            <span class="title">快捷功能</span>
          </div>
          <el-button class="indexBtn" size="small" text @click="shortcutsAdd"
            >设置</el-button
          >
        </div>
      </template>
      <!-- 快捷功能列表-->
      <div class="box">
        <div
          class="box-item"
          v-for="item in pageObj.shortcutsList"
          :key="item.id"
          @click="router.push(item.menuUrl)"
        >
          <svg-icon :class-name="item.icon" color="#006CB6" size="40px" />
          <div class="box-item-title">{{ item.menuName }}</div>
        </div>
        <div
          v-if="!pageObj.shortcutsList.length > 0"
          class="box-item"
          @click="shortcutsAdd"
        >
          <div class="box-item-title">点击添加快捷入口！</div>
        </div>
      </div>
    </el-card>
    <div class="mt20 flex footer">
      <!-- 审核代办-->
      <el-card style="height: 35.5rem; flex: 1">
        <template #header>
          <div class="card-header flex-items-center">
            <div class="flex-items-center">
              <svg-icon
                class="mr10"
                class-name="shenpidaiban"
                color="#009fff"
                size="20px"
              />
              <span class="title">审核代办</span>
              <span class="total">({{ auditAgentTotal }})</span>
            </div>
            <!-- <el-button
              class="indexBtn"
              size="small"
              text
              @click="router.push('/system/business-config/examineTo')"
              >更多</el-button
            > -->
          </div>
        </template>
        <!-- 表格数据 :loading="state.auditAgentLoading"-->
        <p-table
          style="height: 30rem; overflow: auto"
          :loading="examineObj.auditAgentLoading"
          :isSel="false"
          :index="false"
          :isPagination="false"
          :data="examineObj.auditAgentData"
          :column="column"
        >
          <template #columnCell="{ column, record }">
            <div v-if="column.prop == 'x'">
              <el-link
                type="primary"
                v-if="
                  record.statusDict == '待审核' || record.statusDict == '待处理'
                "
                @click="router.push(`${record.pageUrl}?value=${record.docId}`)"
                >前往处理</el-link
              >
            </div>
          </template>
        </p-table>
      </el-card>
      <el-card style="flex: 0.5" class="ml20">
        <template #header>
          <div class="card-header flex-items-center">
            <div class="flex-items-center">
              <svg-icon
                class="mr10"
                class-name="xiaoxitongzhi"
                color="#009fff"
                size="20px"
              />
              <span class="title">消息提醒</span>
              <span class="total">({{ msgTotal }})</span>
            </div>
            <div>
              <el-button
                class="indexBtn"
                v-show="msgTotal > 0"
                size="small"
                text
                @click="allRead"
                >全部已读</el-button
              >
              <el-button class="indexBtn" size="small" text @click="isChouti"
                >更多</el-button
              >
              <!-- @click="userStore.setMsgIsShow(true)" -->
            </div>
            <!-- 抽屉内容 -->
            <el-drawer
              v-model="drawer"
              title="消息中心"
              size="80%"
              direction="ttb"
            >
              <div>
                <el-radio-group
                  v-model="tabPosition"
                  style="margin-bottom: 15px"
                >
                  <el-radio-button label="未读消息">未读消息</el-radio-button>
                  <el-radio-button label="已读消息">已读消息</el-radio-button>
                </el-radio-group>
                <el-table stripe border :data="TableData">
                  <el-table-column
                    type="selection"
                    width="55"
                    align="center"
                    fixed="left"
                  />
                  <el-table-column
                    label="序号"
                    type="index"
                    width="80"
                  ></el-table-column>
                  <el-table-column
                    label="消息类型"
                    prop="messageType"
                    width="auto"
                  />
                  <el-table-column
                    label="消息内容"
                    prop="messageContent"
                    width="auto"
                  />
                  <el-table-column
                    label="告警时间"
                    prop="warnTime"
                    width="auto"
                  />
                  <el-table-column label="操作" width="auto">
                    <template #default="scope"> </template>
                  </el-table-column>
                </el-table>
                <div class="pagination">
                  <pagination
                    :total="state.total"
                    v-model:page="drawerQuery.pageNum"
                    v-model:limit="drawerQuery.pageSize"
                    @pagination="getList"
                  />
                </div>
              </div>
            </el-drawer>
          </div>
        </template>
        <div
          class="msgBox"
          style="height: 30rem; overflow: auto"
          v-infinite-scroll="loadingChange"
        >
          <div
            class="message"
            @click="read(item)"
            v-for="item in msgObj.messageData"
            :key="item.id"
          >
            <div class="top">
              <div class="left">
                <div
                  class="staus"
                  :class="{ okStaus: item.readMark == '1' }"
                ></div>
                <div class="name" :class="{ textStaus: item.readMark == '1' }">
                  {{ item.messageType }}
                </div>
              </div>
              <div class="right" :class="{ textStaus: item.readMark == '1' }">
                {{ item.warnTime }}
              </div>
            </div>
            <div class="content" :class="{ textStaus: item.readMark == '1' }">
              {{ item.messageContent }}
            </div>
          </div>
          <div class="loading-1">
            <p v-if="msgObj.msgLoading">Loading...</p>
          </div>

          <el-empty
            description="暂无消息"
            v-if="!msgObj.messageData.length > 0 && !msgObj.msgLoading"
          >
            <el-button type="primary" @click="getMessage">刷新</el-button>
          </el-empty>
        </div>
      </el-card>
    </div>
    <!-- eacharts -->
    <!-- <div class="eacharts-box" v-if="userStore.workbenchDataType == 1">
      <el-card class="eacharts-item">
        <Echarts title="前五大客户销售占比(元)" :data="echartsObj.customerData" />
      </el-card>
      <el-card class="eacharts-item">
        <Echarts title="前五大供应商采购占比(元)" :data="echartsObj.supplierData" />
      </el-card>
      <el-card class="eacharts-item">
        <Echarts title="成品库存金额" :data="echartsObj.finishAmount" />
      </el-card>
      <el-card class="eacharts-item">
        <Echarts title="原料库存金额" :data="echartsObj.rawAmountData" />
      </el-card>
    </div> -->
    <!-- 快捷功能弹窗 -->
    <p-dialog
      width="40.5rem"
      title="快捷功能"
      v-model="pageObj.shortcutsShow"
      :loading="pageObj.btnloading"
      @ok="shortcutsSub"
      @close="pageObj.shortcutsShow = false"
    >
      <el-transfer
        :disabled="pageObj.disabled"
        :titles="['未选择', '已选择']"
        v-model="pageObj.idStr"
        filterable
        :filter-method="filterMethod"
        :data="pageObj.pageList"
        :props="{
          label: 'menuName',
          key: 'menuId',
        }"
        @change="rightPageChange"
      />
    </p-dialog>
  </div>
</template>
<style scoped lang="scss">
.shortcuts-box {
  margin: 0 25px;
  margin-top: 20px;
}

.card-header {
  display: flex;

  justify-content: space-between;
}

.footer {
  margin: 0 25px;
  margin-top: 1.25rem;
}

.box {
  width: 100%;
  display: flex;
  align-items: center;

  .box-item {
    width: 6rem;
    margin-right: 25px;
    display: flex;
    transition: all 0.5s;
    flex-direction: column;
    align-items: center;
    // border: 1px solid #d4cece;
    padding: 0 10px;
    padding-top: 10px;
    border-radius: 0.625rem;
    cursor: pointer;

    .box-item-title {
      margin-bottom: 20px;
      font-weight: 600;
    }

    &:hover {
      box-shadow: #333333;
      // border: 1px solid #000;
      box-shadow: 0px 5px 2px 5px rgba(57, 57, 57, 0.2);
    }
  }
}

.msgBox {
  overflow: auto;

  .message {
    padding: 15px;
    border: 1px solid #dcdfe6;
    border-top: 0px solid #dcdfe6;
    cursor: pointer;

    &:nth-child(1) {
      border-top: 1px solid #dcdfe6;
    }

    .top,
    .left {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #181818;
      line-height: 44px;

      .staus {
        width: 10px;
        height: 10px;
        background: #006cb6;
        border-radius: 50%;
        margin-right: 11px;
      }

      .okStaus {
        background: #999999;
      }
    }

    .right {
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #999999;
      line-height: 44px;
    }

    .content {
      margin-left: 20px;
      font-size: 14px;
      color: #666674;
    }

    .textStaus {
      color: #a9aaac9e;
    }
  }
}

// eacharts
.eacharts-box {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
}

.eacharts-item {
  margin: 15px 25px;
  flex: 1;
  height: 400px;
  width: 54.85rem;
  min-width: 40rem;
}

.eacharts-item ::v-deep .el-card__body {
  width: 100%;
  height: 100%;
}
</style>